package com.jspgou.cms.action.front;

import static com.jspgou.cms.Constants.MEMBER_SYS;

import java.util.List;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.cms.kuaidi100;
import com.jspgou.cms.entity.Cart;
import com.jspgou.cms.entity.Discuss;
import com.jspgou.cms.entity.Order;
import com.jspgou.cms.entity.OrderItem;
import com.jspgou.cms.entity.OrderReturn;
import com.jspgou.cms.entity.Payment;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.entity.ProductFashion;
import com.jspgou.cms.entity.Shipping;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.ShopMemberAddress;
import com.jspgou.cms.entity.ShopPaymentorder;
import com.jspgou.cms.entity.ShopScore;
import com.jspgou.cms.manager.DiscussMng;
import com.jspgou.cms.manager.OrderMng;
import com.jspgou.cms.manager.OrderReturnMng;
import com.jspgou.cms.manager.PaymentMng;
import com.jspgou.cms.manager.ProductFashionMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.ShippingMng;
import com.jspgou.cms.manager.ShopMemberAddressMng;
import com.jspgou.cms.manager.ShopMemberMng;
import com.jspgou.cms.manager.ShopScoreMng;
import com.jspgou.cms.service.ShoppingSvc;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.FrontUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.cms.web.threadvariable.MemberThread;
import com.jspgou.common.hibernate3.Updater;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Global;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.GlobalMng;
import com.jspgou.core.web.WebErrors;
import com.jspgou.core.web.front.FrontHelper;
import com.jspgou.core.web.front.URLHelper;

@Controller
public class OrderAct {
	/**
	 * 我的订单
	 */
	private static final String MY_ORDER = "tpl.myOrder";
	private static final String MY_RETURN_ORDER = "tpl.myReturnOrder";
	private static final String MY_ORDER_VIEW = "tpl.myOrderView";
	private static final String MY_ORDERCOMPLETE="tpl.orderComplete";
	private static final String MY_ORDERSPAY="tpl.ordersPay";
	
	private static final String VIEW_LOGISTIC="tpl.viewLogistic";
	
    //订单列表
	@RequestMapping(value = "/order/myorder*.jspx")
	public String myOrder(String cl,Integer ass,Integer status,String productName,String userName,String code1, Long paymentId,
			Integer paymentStatus,Integer shippingStatus,Long shippingId, String startTime,String endTime,
			Double startOrderTotal,Double endOrderTotal,Integer isRefunded,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		model.addAttribute("historyProductIds", "");
		model.addAttribute("cl",cl);
		Cookie[] cookie = request.getCookies();
		for (int i = 0; i < cookie.length; i++) {
			if (cookie[i].getName().equals("shop_record")) {
				String str = cookie[i].getValue();
				model.addAttribute("historyProductIds", str);
				break;
			}
		}
		List<Shipping> shippingList = shippingMng.getList(web.getId(),null,null, true);
		List<Payment> paymentList = paymentMng.getList(web.getId(), true);
		model.addAttribute("paymentList", paymentList);
		model.addAttribute("shippingList", shippingList);
		model.addAttribute("status", status);
		model.addAttribute("productName", productName);
		model.addAttribute("paymentStatus", paymentStatus);
		model.addAttribute("shippingStatus", shippingStatus);
		model.addAttribute("ass", ass);
		if(StringUtils.isBlank(userName)){
			model.addAttribute("userName", null);
		}else{
		  model.addAttribute("userName", userName);
		}
		if(StringUtils.isBlank(code1)){
			model.addAttribute("code1", null);
		}else{
		  model.addAttribute("code1", code1);
		}
		if(StringUtils.isBlank(startTime)){
			model.addAttribute("startTime", null);
		}else{
		  model.addAttribute("startTime", startTime);
		}
		if(StringUtils.isBlank(endTime)){
			model.addAttribute("endTime", null);
		}else{
		  model.addAttribute("endTime", endTime);
		}
		model.addAttribute("isRefunded", isRefunded);
		model.addAttribute("paymentId", paymentId);
		model.addAttribute("shippingId", shippingId);
		model.addAttribute("member", member);
		model.addAttribute("startOrderTotal",startOrderTotal);
		model.addAttribute("endOrderTotal", endOrderTotal);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,MY_ORDER), request);
	}
	
	//退换货订单列表
	@RequestMapping(value = "/order/myReturnOrder*.jspx")
	public String myReturnOrder(String cl,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Integer pageNo=URLHelper.getPageNo(request);
		//Pagination pagination =manager.getOrderByReturn(member.getId(), pageNo, 10);
		model.addAttribute("member", member);
		model.addAttribute("cl",cl);
		model.addAttribute("pageNo",pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,MY_RETURN_ORDER), request);
	}
	
	public String getHistoryProductIds(HttpServletRequest request){
		String str = null ;
		Cookie[] cookie = request.getCookies();
		int num = cookie.length;
		for (int i = 0; i < num; i++) {
			if (cookie[i].getName().equals("shop_record")) {
				str = cookie[i].getValue();
				break;
			}
		}
		return str;
	}
	
	//生成订单
	@RequestMapping(value = "/order/order_shipping.jspx")
	public String orderShipping(Long deliveryMethodSelector[],
			Long paymentMethodId,Long deliveryInfo,Long[] cartItemId,String comments,HttpServletRequest request,
			HttpServletResponse response, ModelMap model,String memberCouponId) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Cart cart = shoppingSvc.getCart(member, request, response);
		if(member==null){
			return "redirect:../login.jspx";
		}
		if(cart==null){
			return "redirect:../cart/shopping_cart.jspx";
		}
		ShopMemberAddress shopMemberAddress=shopMemberAddressMng.findById(deliveryInfo);
		Payment pay=paymentMng.findById(paymentMethodId);
		
		ShopPaymentorder shopPaymentorder=manager.createOrders(deliveryMethodSelector,request.getRemoteAddr(),comments,cart,cartItemId,shopMemberAddress,pay, member, web.getId(),memberCouponId);
		shoppingSvc.getCart(member, request, response);
		//model.addAttribute("order", order);
		model.addAttribute("shopPaymentorder", shopPaymentorder);
		ShopFrontHelper.setCommonData(request, model, web);
	
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,MY_ORDERSPAY), request);		
	}
	
	//立即购买生成订单
	@RequestMapping(value = "/order/order_shipping_buyNow.jspx", method = RequestMethod.POST)
	public String buyNowOrderShipping(Long deliveryMethodSelector[],Long productId,Integer itemNumBox,
			Long paymentMethodId,Long deliveryInfo,String comments,HttpServletRequest request,
			HttpServletResponse response, ModelMap model,String memberCouponId) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:login.jspx";
		}
		ShopMemberAddress shopMemberAddress=shopMemberAddressMng.findById(deliveryInfo);
		Payment pay=paymentMng.findById(paymentMethodId);
		Product entity = productMng.findById(productId);
		Order order=manager.buyNowCreateOrder(entity,itemNumBox,deliveryMethodSelector,request.getRemoteAddr(),comments,shopMemberAddress,pay, member, web.getId(),memberCouponId);
		
		shoppingSvc.getCart(member, request, response);
		model.addAttribute("order", order);
		//model.addAttribute("order", shopPaymentorder);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,MY_ORDERCOMPLETE), request);		
	}

	//修改订单
	@RequestMapping(value = "/order/editOrder.jspx")
	public void editOrder(Long orderId,Integer status,HttpServletRequest request,
			HttpServletResponse response) throws JSONException {
		ShopMember member=CmsUtils.getMember(request);
		JSONObject json=new JSONObject();
		Product product=null;
		ShopScore shopScore=null;
		ProductFashion fashion=null;
		//获取销售订单
		Order order=manager.findById(orderId);
		//获得销售订单状态
		int state  = order.getStatus();
		if(status==13){
			if(order.getStatus()==11){
				//没有发货要求退款
					order.setDeliver(true);
			}
	    }else if(status==18){
	    	member.setScore(member.getScore()-order.getScore());
	    	for(OrderItem item:order.getItems()){
				product=item.getProduct();
				//设置库存
				product.setStockCount(item.getCount()+product.getStockCount());		
				if(item.getProductFash()!=null){
					fashion=item.getProductFash();
					fashion.setSaleCount(fashion.getSaleCount()+item.getCount());
					productFashionMng.update(fashion);
				}
				Updater<Product> updater = new Updater<Product>(product);
				productMng.updateByUpdater(updater);	
				shopScore=shopScoreMng.findByOrderItemId(item.getId());
				shopScoreMng.deleteById(shopScore.getId());
			}
	    	shopMemberMng.update(member);
	    }else if(status==19){
	    	for(OrderItem item:order.getItems()){
				Discuss discuss=new Discuss();
				discuss.setMember(member);
				discuss.setProduct(item.getProduct());
				discuss.setOrderItem(item);
				discuss.setStore(item.getProduct().getStore());
				discuss.setStart(false);
				discussMng.save(discuss);
				shopScore=shopScoreMng.findByOrderItemId(item.getId());
				shopScore.setStatus(true);
				shopScoreMng.update(shopScore);
			}
	    	member.setScore(member.getScore()+ order.getScore());
	    	shopMemberMng.update(member);
	    }else if(status==20){
			member.setFreezeScore(member.getFreezeScore()-order.getScore());
			for(OrderItem item:order.getItems()){
				product=item.getProduct();
				//设置库存
				product.setStockCount(item.getCount()+product.getStockCount());
				
				if(item.getProductFash()!=null){
					fashion=item.getProductFash();
					fashion.setSaleCount(fashion.getSaleCount()+item.getCount());
					productFashionMng.update(fashion);
				}
				Updater<Product> updater = new Updater<Product>(product);
				productMng.updateByUpdater(updater);	
				shopScore=shopScoreMng.findByOrderItemId(item.getId());
				shopScoreMng.deleteById(shopScore.getId());
			}
		}
		order.setStatus(status);
		order=manager.updateByUpdater(order);
		json.put("success", true);
		ResponseUtils.renderJson(response, json.toString());
	}
	
	//删除订单
	@RequestMapping(value = "/order/deleteOrder.jspx",method=RequestMethod.POST)
	public void deleteOrder(Long orderId,HttpServletRequest request,
			HttpServletResponse response) throws JSONException  {
		JSONObject json=new JSONObject();
		try{
			if(orderId!=null){				
				manager.deleteById(orderId);
			}
			json.put("success", true);
			ResponseUtils.renderJson(response, json.toString());	
		}catch(Exception e){
			json.put("success", false);
		    json.put("fail",productMng.getTipFile("delete.orderReturn"));
		    ResponseUtils.renderJson(response, json.toString());
		}
	}
	
	//取消订单
	@RequestMapping(value="/order/abolishOrder.jspx",method=RequestMethod.POST)
	public void abolishOrder(Long orderId,HttpServletRequest request,
			HttpServletResponse response) throws JSONException{
		JSONObject json=new JSONObject();
		ShopMember member=MemberThread.get();
		if(orderId!=null){
			Order order=manager.findById(orderId);
			order.setStatus(3);
			Set<OrderItem> set=order.getItems();
			//处理库存
			for(OrderItem item:set){
				Product product=item.getProduct();
				if(item.getProductFash()!=null){
					ProductFashion fashion=item.getProductFash();
					fashion.setStockCount(fashion.getStockCount()+item.getCount());
					product.setStockCount(product.getStockCount()+item.getCount());
					productFashionMng.update(fashion);
				}else{
					product.setStockCount(product.getStockCount()+item.getCount());
				}
				productMng.update(product);
			}
			//会员冻结的积分
			member.setFreezeScore(member.getFreezeScore()-order.getScore());
			shopMemberMng.update(member);
			List<ShopScore> list=shopScoreMng.getlist(order.getCode());
			for(ShopScore s:list){
				shopScoreMng.deleteById(s.getId());
			}
			manager.updateByUpdater(order);
		}
		json.put("success", true);
		ResponseUtils.renderJson(response, json.toString());
	}
	
	//确认收货
	@RequestMapping(value="/order/accomplishOrder.jspx")
	public void accomplishOrder(Long orderId,HttpServletRequest request,
			HttpServletResponse response) throws JSONException{
		JSONObject json=new JSONObject();
		ShopMember member=MemberThread.get();
		if(orderId!=null){
			Order order=manager.findById(orderId);
			order.setStatus(4);
			//会员冻结的积分
			member.setFreezeScore(member.getFreezeScore()-order.getScore());
			member.setScore(member.getScore()+order.getScore());
			shopMemberMng.update(member);
			List<ShopScore> list=shopScoreMng.getlist(order.getCode());
			for(ShopScore s:list){
				s.setStatus(true);
				shopScoreMng.update(s);
			}
			manager.updateByUpdater(order);
		}
		json.put("success", true);
		ResponseUtils.renderJson(response, json.toString());
	}
	
	//确认收货
	@RequestMapping(value="/order/accomplishyuShouOrder.jspx")
	public void accomplishyuShouOrder(Long orderId,HttpServletRequest request,
			HttpServletResponse response) throws JSONException{
		JSONObject json=new JSONObject();
		if(orderId!=null){
			Order order=manager.findById(orderId);
			order.setStatus(4);
			manager.updateByUpdater(order);
		}
		json.put("success", true);
		ResponseUtils.renderJson(response, json.toString());
	}
	
	/**
	 * 退货订单的发货
	 * @param id
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/order/shipments.jspx")
	public String shipments(Long id,HttpServletRequest request, ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		WebErrors errors=validateOrderReturnView(id,member,request);
		if(errors.hasErrors()){
			return FrontHelper.showError(errors, web, model, request);
		}
		OrderReturn entity =orderReturnMng.findById(id);
		//退货订单状态改为“待收货”
		entity.setStatus(4);
		orderReturnMng.update(entity);
		return "redirect:../order/myReturnOrder.jspx";
	}
	
	/**
	 * 退货确认
	 * @param id
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/order/accomplish.jspx")
	public String accomplish(Long id, HttpServletRequest request,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		WebErrors errors=validateOrderReturnView(id,member,request);
		if(errors.hasErrors()){
			return FrontHelper.showError(errors, web, model, request);
		}
		OrderReturn entity =orderReturnMng.findById(id);
		//退货订单状态改为“已完成”
		entity.setStatus(7);
		Order order=orderReturnMng.findById(id).getOrder();
		//把订单的状态改为了“已取消”
		order.setStatus(3);
		manager.updateByUpdater(order);
		Set<OrderItem> set = entity.getOrder().getItems();
		//处理库存(前提是“必须是‘已发货’的订单”)
		if(entity.getOrder().getShippingStatus()==2){			
			for(OrderItem item:set){	
				Product product=item.getProduct();
				if(item.getProductFash()!=null){
					ProductFashion fashion=item.getProductFash();
					fashion.setStockCount(fashion.getStockCount()+item.getCount());
					product.setStockCount(product.getStockCount()+item.getCount());
					productFashionMng.update(fashion);
				}else{
					product.setStockCount(product.getStockCount()+item.getCount());
				}
				productMng.update(product);
			}
		}
		//会员冻结的积分
		member.setFreezeScore(member.getFreezeScore()-entity.getOrder().getScore());
		shopMemberMng.update(member);
		List<ShopScore> list = shopScoreMng.getlist(entity.getOrder().getCode());
		for(ShopScore s:list){
			shopScoreMng.deleteById(s.getId());
		}
		orderReturnMng.update(entity);
	    return "redirect:../order/myReturnOrder.jspx";
	}
	
	//查看订单详情
	@RequestMapping(value = "/order/myOrderView.jspx")
	public String myOrderView(Long orderId, HttpServletRequest request,
			ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		WebErrors errors = validateOrderView(orderId, member, request);
		if (errors.hasErrors()) {
			return FrontHelper.showError(errors, web, model, request);
		}
		Order order = manager.findById(orderId);
		model.addAttribute("order", order);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,
				MY_ORDER_VIEW), request);
	}
	
	//查看物流详情
	@RequestMapping(value="/order/viewLogistic.jspx")
	public String  viewLogistic(Long orderId,String yushou,HttpServletRequest request,
			ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if (member == null) {
			return "redirect:../login.jspx";
		}
		if(orderId==null){
			if(yushou!=null){
				return "redirect:../yushou/myorder.jspx";
			}
			return "redirect:../order/myorder.jspx";
		}else{
			Order order=manager.findById(orderId);
			//获得物流公司代码
			String com=order.getShipping().getLogistics().getCompanyCode();
			//获得货运单号
			String nu=order.getInvoiceNo();
			//获得快递查询密钥
			Global global=globalMng.findIdkey();
			String idkey=global.getIdkey();
			String kua=new kuaidi100().searchkuaiDiInfo(idkey, com, nu);
			model.addAttribute("nu", nu);
			model.addAttribute("yushou", yushou);
			model.addAttribute("kua", kua);
			model.addAttribute("order", order);
		}
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request, VIEW_LOGISTIC), request);
	}
	
	private WebErrors validateOrderView(Long orderId, ShopMember member,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNull(orderId, "orderId")) {
			return errors;
		}
		Order order = manager.findById(orderId);
		if (errors.ifNotExist(order, Order.class, orderId)) {
			return errors;
		}
		if (!order.getMember().getId().equals(member.getId())) {
			errors.noPermission(Order.class, orderId);
			return errors;
		}
		return errors;
	}
	
	private WebErrors validateOrderReturnView(Long orderReturnId,ShopMember member,
			HttpServletRequest request){
		WebErrors errors=WebErrors.create(request);
		if(errors.ifNull(orderReturnId, "orderReturnId")){
			return errors;
		}
		OrderReturn orderReturn=orderReturnMng.findById(orderReturnId);
		if(errors.ifNotExist(orderReturn, OrderReturn.class, orderReturnId)){
			return errors;
		}
		if (!orderReturn.getOrder().getMember().getId().equals(member.getId())) {
			errors.noPermission(OrderReturn.class, orderReturnId);
			return errors;
		}
		return errors;
	}
	
	@Autowired
	private OrderMng manager;
	@Autowired
	private DiscussMng discussMng;
	@Autowired
	private ProductMng productMng;
	@Autowired
	private PaymentMng paymentMng;
	@Autowired
	private ShippingMng shippingMng;
	@Autowired
	private ShoppingSvc shoppingSvc;
	@Autowired
	private ShopScoreMng shopScoreMng;
	@Autowired
	private ShopMemberMng shopMemberMng;
	@Autowired
	private ProductFashionMng productFashionMng;
	@Autowired
	private ShopMemberAddressMng shopMemberAddressMng;
	@Autowired
	private GlobalMng globalMng;
	@Autowired
	private OrderReturnMng orderReturnMng;
}
